package cn.ffcs.product.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import cn.ffcs.base.service.BaseService;
import cn.ffcs.base.web.PageControl;
import cn.ffcs.common.dao.IAttachDAO;
import cn.ffcs.common.model.Attach;
import cn.ffcs.organ.dao.ILinkMethodDAO;
import cn.ffcs.organ.model.LinkMethod;
import cn.ffcs.organ.model.Person;
import cn.ffcs.product.model.Product;
import cn.ffcs.product.model.ProductManager;
import cn.ffcs.product.model.ProductReference;
import cn.ffcs.product.dao.IProductDAO;
import cn.ffcs.product.dao.IProductManagerDAO;
import cn.ffcs.product.dao.IProductReferenceDAO;
import cn.ffcs.ref.dao.IProductRefSortDAO;
import cn.ffcs.ref.model.ProductRefSort;
import cn.ffcs.security.model.User;
import cn.ffcs.sort.model.ProductSort;
import cn.ffcs.system.dict.dao.IDictDAO;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * 字典类型业务逻辑层实现<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author g.huangjx
 * @version $Id$
 */
public class ProductService<D extends Product> extends BaseService<D> implements
        IProductService<D>
{
    /**产品ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private IProductDAO productDAO;
    /**附件ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private IAttachDAO attachDAO;// 附件DAO
    /**产品管理员ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private IProductManagerDAO productManagerDAO;
    /**联系方式ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private ILinkMethodDAO linkMethodDAO;
    /**产品资料ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private IProductRefSortDAO productRefSortDAO;
    /**字典ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private IDictDAO dictDAO;
    /**产品资料ＤＡＯ**/
    @SuppressWarnings("unchecked")
    private IProductReferenceDAO productReferenceDAO;

    /**
     * 删除产品所有属性
     * @param b
     * @return
     */
    public void deleteProductInfo(String productId)
    {
        productDAO.deleteProductInfo(productId);
    }

    /**
     * 循环保存产品属性
     * @param b
     * @return
     */
    public void saveProductInfo(D d, String addInfos, String addValues)
    {
        productDAO.saveProductInfo(d, addInfos, addValues);
    }

    /**
     *产品修改，包括上传附件和动态属性修改
     * @param b
     * @return
     */
    public void saveAll(D d, String addInfos, String addValues,
            List<File> uploads, List<String> fileNames, String[] delIDs,
            String[] mainPersons, String[] persons)
    {
        /*
         * 删除已有的动态属性
         */
        if (d.getId() != null)
        {
            deleteProductInfo(d.getId().toString());
        }
        /*
         * 新增动态属性
         */
        if (addInfos != null && !addInfos.equals(""))
        {
            saveProductInfo(d, addInfos, addValues);
        }
        /*
         * 删除已有的产品负责人
         */
        if (d.getId() != null)
        {
            deletePerson(d.getId().toString());
        }
        /*
         * 新增产品主要负人
         */
        if (mainPersons != null && mainPersons.length > 0)
        {
            for (int i = 0; i < mainPersons.length; i++)
            {
                ProductManager productManager = new ProductManager();
                Person person = new Person();
                person.setId(new Integer(mainPersons[i].trim()));
                productManager.setProduct(d);
                productManager.setPerson(person);
                productManager.setIsPrimary("1");
                // 设置有效时间
                productManager.setBegin(getCurrSysdate());
                Long l = Long.valueOf("9783941568000");
                Date end = new Date(l);
                productManager.setEnd(end);
                productManagerDAO.save(productManager);

            }
        }
        /*
         * 新增产品其它负责人
         */
        if (persons != null && persons.length > 0)
        {
            for (int i = 0; i < persons.length; i++)
            {
                ProductManager productManager = new ProductManager();
                Person person = new Person();
                person.setId(new Integer(persons[i]));
                productManager.setProduct(d);
                productManager.setPerson(person);
                productManager.setIsPrimary("0");
                // 设置有效时间
                productManager.setBegin(getCurrSysdate());
                Long l = Long.valueOf("9783941568000");
                Date end = new Date(l);
                productManager.setEnd(end);
                productManagerDAO.save(productManager);
            }
        }
        /*
         * 产品基本信息修改
         */
        /*
         * Set pers = new HashSet(); for(String person:persons){
         * pers.add(person); }
         */
        // d.setProductManagers(productManagers)
        saveOrUpdate(d);
        /*
         * 附件新增
         */
        if (uploads != null)
        {
            int i = 0;
            for (i = 0; i < uploads.size(); i++)
            {
                try
                {
                    File file = uploads.get(i);
                    byte[] result = new byte[512 * 1024];
                    result = FileUtils.readFileToByteArray(file);
                    FileUtils.forceDelete(file);
                    String fileName = fileNames.get(i);
                    String fullName = fileName;
                    String name = fullName.substring(0, fullName.indexOf("."));
                    String prefix = fullName.substring(
                            fullName.indexOf(".") + 1, fullName.length());

                    Attach attach = new Attach();
                    attach.setContent(result);
                    attach.setFileType("pic");
                    attach.setFullName(fullName);
                    attach.setName(name);
                    attach.setPrefix(prefix);
                    attach.setRefEntity(d.getClass().getName());
                    attach.setRefEntityID(d.getId().toString());
                    User currUser = ApplicationContextUtil
                            .getUserContextObject().getCurrUser();
                    if (currUser != null)
                        attach.setCreator(currUser.getUserID());
                    attach.setIsPublish(0);// 默认为不发布
                    // 设置有效时间
                    attach.setBegin(getCurrSysdate());
                    Long l = Long.valueOf("9783941568000");
                    Date end = new Date(l);
                    attach.setEnd(end);
                    attachDAO.save(attach);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        // 附件删除
        if (delIDs != null && delIDs.length > 0)
        {
            for (String id : delIDs)
            {
                attachDAO.deleteById(id);
            }
        }

    }

    /**
     *目录下的产品修改，包括上传附件和动态属性修改
     * @param b
     * @return
     */
    public void saveAll(D d, String addInfos, String addValues,
            List<File> uploads, List<String> fileNames, String[] delIDs,
            String[] mainPersons, String[] persons, ProductSort productSort)
    {
        Integer productId = d.getId();
        saveAll(d, addInfos, addValues, uploads, fileNames, delIDs,
                mainPersons, persons);
        ProductRefSort productRefSort = new ProductRefSort();
        productRefSort.setProduct(d.getId().toString());
        if (!"0".equals(productRefSort.getSort())&&(productId == null || productId.intValue() == 0))
        {// 新增的时候才操作
            productRefSort.setSort(productSort.getId().toString());
            User currUser = ApplicationContextUtil
            .getUserContextObject().getCurrUser();
            if (currUser != null)
                productRefSort.setCreator(currUser.getUserID());
            productRefSort.setBegin(getCurrSysdate());
            Long l = Long.valueOf("9783941568000");
            Date end = new Date(l);
            productRefSort.setEnd(end);
            productRefSortDAO.save(productRefSort);// 保存目录关联产品
        }
    }

    public void saveAll(D d, String addInfos, String addValues,
            List<File> uploads, List<String> fileNames, String[] delIDs,
            String[] mainPersons, String[] persons,String [] sortIds)
    {
        Integer productId = d.getId();
        saveAll(d, addInfos, addValues, uploads, fileNames, delIDs,
                mainPersons, persons);
        ProductRefSort productRefSort = new ProductRefSort();
//        List<ProductRefSort> refSorts;
        productRefSortDAO.delete(productRefSort, "product", d.getId().toString());
        if (sortIds!=null)
        {// 新增的时候才操作
            for(int i=0;i<sortIds.length;i++){
                if(sortIds[i]!=null&&!"".equals(sortIds[i])){
//                    Criterion cond1 = Restrictions.eq("sort", sortIds[i]);
//                    Criterion cond2 = Restrictions.eq("product", d.getId().toString());
//                    Criterion cond = Restrictions.and(cond1, cond2);
//                    refSorts=productRefSortDAO.findBy(cond);
                    productRefSort = new ProductRefSort();
                    productRefSort.setProduct(d.getId().toString());
                    productRefSort.setSort(sortIds[i]);
                    
                    User currUser = ApplicationContextUtil
                    .getUserContextObject().getCurrUser();
                    if (currUser != null)
                        productRefSort.setCreator(currUser.getUserID());
                    productRefSort.setBegin(getCurrSysdate());
                    Long l = Long.valueOf("9783941568000");
                    Date end = new Date(l);
                    productRefSort.setEnd(end);
                    productRefSortDAO.save(productRefSort);// 保存目录关联产品
                }
            }
        }
    }
    
    /**
     * 删除数据
     * @return
     */
    public void remove(D d)
    {
        /*
         * 删除已有的动态属性、已有的产品负责人、附件、产品信息,产品目录关联产品
         */
        if (d.getId() != null)
        {
            // 删除产品信息
            deleteProductInfo(d.getId().toString());
            // 删除产品管理人员信息
            deletePerson(d.getId().toString());
            // 删除产品目录信息
            ProductRefSort productRefSort = new ProductRefSort();
            productRefSort.setProduct(d.getId().toString());
            productRefSortDAO.delete(productRefSort, "product", d.getId()
                    .toString());
            // 删除产品相关附件
            attachDAO.deleteAttachByEntity(d);
            productDAO.deleteProductRefSort(d.getId());// 产品目录关联产品
            super.remove(d);
        }
        return;
    }

    /**
     * 批量删除数据
     * @return
     */
    public void batchDel(String[] ids)
    {
        for (String id : ids)
        {
            D d = super.findById(new Integer(id));
            this.remove(d);
        }
        return;
    }

    /**
     * 获取产品展示信息
     * @param product
     * @param lMainPerson
     * @param lGenPersons
     */
    public void showProductInfoById(Product product, List<Person> lMainPerson,
            List<Person> lGenPersons)
    {

        if (product != null && product.getId() != 0)
        {
            product = (D) productDAO.findById(product.getId());
            Iterator it = product.getProductManagers().iterator();

            lMainPerson = new ArrayList<Person>();
            lGenPersons = new ArrayList<Person>();

            while (it.hasNext())
            {
                ProductManager productManager = (ProductManager) it.next();
                Person person = productManager.getPerson();

                // 获取联系方式
                // Person
                // managerInfo=(Person)personService.findById(person.getId());
                // //productManager.setPerson(managerInfo);
                Criterion cond = Restrictions.eq("person.id", person.getId());
                List<LinkMethod> linkMethods = linkMethodDAO.findBy(cond);
                person.setLinkMethods(linkMethods);
                if (productManager.getIsPrimary().equals("1"))
                {
                    lMainPerson.add(person);
                }
                else
                {
                    lGenPersons.add(person);
                }
            }
        }

    }

    /**
     * 获取管理员联系方式
     * @param p
     * @return
     */
    public List<LinkMethod> getPMLinkMethods(Person p)
    {
        Criterion cond = Restrictions.eq("person.id", p.getId());
        return linkMethodDAO.findBy(cond);
    }

    /**
     * 删除产品所有负责人
     * @param b
     * @return
     */

    public void deletePerson(String productId)
    {
        productDAO.deletePerson(productId);
    }

    /**
     * 根据产品目录查产品
     * @param p
     * @return
     */
    public List<Product> findBySort(String sortId)
    {
        return productDAO.findBySort(sortId);
    }
    
    /**
     * 获取产品资料信息，包括业务管理规范和产品说明书、产品视图
     * @param prodID
     */
    public List<ProductReference> findProdRefsById(int prodID)
    {
        List<ProductReference> results=new ArrayList<ProductReference>();
        // 获取产品资料信息，包括业务管理规范和产品说明书、产品视图
        Criterion cond1 = Restrictions.eq("keyValue", "BUSIMETHOD");
        Criterion cond2 = Restrictions.eq("keyValue", "PRODUCT_REFERENCE");
        Criterion cond3 = Restrictions.eq("keyValue", "PRODUCT_VIEW");
        Criterion cond4 = Restrictions.or(cond1, cond2);
        Criterion cond = Restrictions.or(cond3, cond4);
        //产品字典信息
        List<Dict> dicts = this.dictDAO.findBy(cond);
        if (dicts != null && dicts.size() > 0)
        {
            for (Dict dict : dicts)
            {
                Criterion condRef1 = Restrictions.eq("product.id", prodID);
                Criterion condRef2 = Restrictions.eq("referenceType.id", dict.getId());
                Criterion condRef=Restrictions.and(condRef1, condRef2);
                List<ProductReference> productReferences=productReferenceDAO.findBy(condRef);
                if (productReferences!=null && productReferences.size()>0){
                    for (ProductReference pr:productReferences){
                        Criterion condA1 = Restrictions.eq("refEntity", pr.getClass().getName());
                        Criterion condA2 = Restrictions.eq("refEntityID", pr.getId().toString());
                        Criterion condA = Restrictions.and(condA1, condA2);
                        pr.setAttachs(attachDAO.findBy(condA));
                        results.add(pr);
                    }
                }
            }
        }
        
        return results;
    }
    
    public PageControl findByPage(HashMap<String, Object> conds,int currPage, int pageSize){
        return productDAO.findByPage(conds, currPage, pageSize);
    }
    
    /**
     * 获取产品ＤＡＯ
     * @return
     */
    public IProductDAO getProductDAO()
    {
        return productDAO;
    }
    
    /**
     * 设置产品ＤＡＯ
     * @return
     */
    public void setProductDAO(IProductDAO productDAO)
    {
        this.productDAO = productDAO;
    }

    public IAttachDAO getAttachDAO()
    {
        return attachDAO;
    }

    public void setAttachDAO(IAttachDAO attachDAO)
    {
        this.attachDAO = attachDAO;
    }

    public IProductManagerDAO getProductManagerDAO()
    {
        return productManagerDAO;
    }

    public void setProductManagerDAO(IProductManagerDAO productManagerDAO)
    {
        this.productManagerDAO = productManagerDAO;
    }

    /**
     * @return the linkMethodDAO
     */
    public ILinkMethodDAO getLinkMethodDAO()
    {
        return linkMethodDAO;
    }

    /**
     * @param linkMethodDAO the linkMethodDAO to set
     */
    public void setLinkMethodDAO(ILinkMethodDAO linkMethodDAO)
    {
        this.linkMethodDAO = linkMethodDAO;
    }

    /**
     * @return the productRefSortDAO
     */
    public IProductRefSortDAO getProductRefSortDAO()
    {
        return productRefSortDAO;
    }

    public void setProductRefSortDAO(IProductRefSortDAO productRefSortDAO)
    {
        this.productRefSortDAO = productRefSortDAO;
    }

    /**
     * @return the dictDAO
     */
    public IDictDAO getDictDAO()
    {
        return dictDAO;
    }

    /**
     * @param dictDAO the dictDAO to set
     */
    public void setDictDAO(IDictDAO dictDAO)
    {
        this.dictDAO = dictDAO;
    }

    /**
     * @return the productReferenceDAO
     */
    public IProductReferenceDAO getProductReferenceDAO()
    {
        return productReferenceDAO;
    }

    /**
     * @param productReferenceDAO the productReferenceDAO to set
     */
    public void setProductReferenceDAO(IProductReferenceDAO productReferenceDAO)
    {
        this.productReferenceDAO = productReferenceDAO;
    }

}
